import { login } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import { menu } from '@/api/menu'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    menuList: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USR_INFO: (state, object) => {
    state.userInfo = object
  },
  SET_MENU: (state, menuList) => {
    state.menuList = menuList
  }
}

const actions = {
  // 登录方法
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    if (res.code === 200) {
      // 登录成功
      commit('SET_TOKEN', res.data.data.token)
      commit('SET_USR_INFO', res.data.data.username)
      setToken(res.data.data.token)
      // 返回成功的信息
      return 'ok'
    } else {
      // 返回异常的信息
      return Promise.reject(new Error(res.msg))
    }
  },

  // 获取菜单列表
  async getMenuList({ commit }) {
    const res = await menu('tree')
    if (res.code === 200) {
      // 获取是菜单的列表
      const menuList = filterMenu(res.data.data)
      commit('SET_MENU', menuList)
      // 返回成功的信息
      return 'ok'
    } else {
      // 返回异常的信息
      return Promise.reject(new Error(res.msg))
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

function filterMenu(data) {
  return data.filter(item => {
    if (item.is_menu === false) {
      return false
    }
    if (item.children && item.children.length > 0) {
      item.children = filterMenu(item.children)
    }
    return true
  })
}
